package com.wholesale;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.wholesale.beans.Country;
import com.wholesale.beans.UserAddress;
import com.wholesale.datas.WebServiceClient;
import com.wholesale.utils.Constants;

public class AddressLayout extends LinearLayout implements OnClickListener {
	private ViewFlipper viewFlipper;
	private Context context;
	private View baseView;
	private Button leftButton;
	private Button rightButton;
	private TextView headView, address, postalcode, fullname, phone, delete;
	private TextView country, province, city;
	
	private Country countryEntiy;
	private Country provinceEntiy;
	private Country cityEntiy;
	
	private String[] str = null;
	private List<Country> countryList = null;
	private List<Country> provinceList = null;
	private List<Country> cityList = null;
	private List<Country> distractList = null;
	private UserAddress useraddress = null;
	//private ProgressDialog pd;
	private RelativeLayout loadingLayout;
	private int actionType = 0;
	
	private final static int GETCOUNTRY = 10 ;
	private final static int GETPROVINCE = 11 ;
	private final static int GETCITY = 12 ;
	
	private AlertDialog countryDialog ;
	private AlertDialog provinceDialog ;
	private AlertDialog cityDialog ;
	AddressTask addressTask ;

	// 构造函数
	public AddressLayout(final Context context, final ViewFlipper viewFlipper,
			int orderId, final UserAddress useraddress) {
		super(context);
		this.viewFlipper = viewFlipper;
		this.context = context;
		this.useraddress = useraddress;
		// 加载需要的属性，加载方法一的子Layout
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(
				R.layout.addaddress, this);
		leftButton = (Button) baseView.findViewById(R.id.leftBtn);
		leftButton.setText("Back");
		leftButton.setOnClickListener(this);
		rightButton = (Button) baseView.findViewById(R.id.rightBtn);
		rightButton.setOnClickListener(this);
		rightButton.setText("Save");
		headView = (TextView) baseView.findViewById(R.id.title);
		headView.setText("New Address");
		address = (TextView) findViewById(R.id.address_text);
		postalcode = (TextView) findViewById(R.id.postalcode_text);
		fullname = (TextView) findViewById(R.id.fullname_text);
		phone = (TextView) findViewById(R.id.phone_text);
		delete = (TextView) findViewById(R.id.deletebutton);
		delete.setOnClickListener(this);
		country = (TextView) findViewById(R.id.country_text);
		country.setOnClickListener(this);
		province = (TextView) findViewById(R.id.state_text);
		province.setOnClickListener(this);
		city = (TextView) findViewById(R.id.city_text);
		city.setOnClickListener(this);
		/*pd = ProgressDialog.show(context, "prompt", "please wait...", true,
				false);*/
		loadingLayout = (RelativeLayout) baseView
		.findViewById(R.id.loadingLayout);
		if (useraddress != null) {
			fullname.setText(""+useraddress.getConsignee());
			phone.setText(""+useraddress.getMobile());
			address.setText(""+useraddress.getAddress());
			postalcode.setText(""+useraddress.getZipcode());
			country.setText(""+useraddress.getCountryName());
			province.setText(useraddress.getProvinceName());
			city.setText(""+useraddress.getCityName());
			delete.setVisibility(View.VISIBLE);
			actionType = 1;
			countryEntiy = new Country();
			countryEntiy.setRegionId(useraddress.getCountry());
			countryEntiy.setRegionName(useraddress.getCountryName());
			provinceEntiy = new Country();
			provinceEntiy.setRegionId(useraddress.getProvince());
			provinceEntiy.setRegionName(useraddress.getProvinceName());
			cityEntiy = new Country();
			cityEntiy.setRegionId(useraddress.getCity());
			cityEntiy.setRegionName(useraddress.getCityName());
		}else{
			actionType = 0;
			this.useraddress = new UserAddress();
		}

	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) ((Activity) getContext())
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		switch (v.getId()) {
		case R.id.leftBtn:
			imm.hideSoftInputFromWindow(leftButton.getWindowToken(), 0);
				
			viewFlipper.showPrevious();
			viewFlipper.removeView(this);
			break;
		case R.id.rightBtn:
			
			imm.hideSoftInputFromWindow(rightButton.getWindowToken(), 0);
			
			operate();

			break;
		case R.id.deletebutton:
			
			
			imm.hideSoftInputFromWindow(delete.getWindowToken(), 0);
			
			actionType = 2;
			operate();
			break;
		case R.id.country_text:
		
			imm.hideSoftInputFromWindow(country.getWindowToken(), 0);
			
			if(countryEntiy == null || countryDialog == null){
				if(addressTask != null){
					addressTask.cancel(true);
				}
				addressTask = new AddressTask(context);
				addressTask.execute(GETCOUNTRY);
			}else{
				countryDialog.show();
			}
			
			break ;
		case R.id.state_text:
			imm.hideSoftInputFromWindow(province.getWindowToken(), 0);
			
			if(countryEntiy != null ){
				if(provinceEntiy == null || provinceDialog == null ){
					if(addressTask != null){
						addressTask.cancel(true);
					}
					addressTask = new AddressTask(context);
					addressTask.execute(GETPROVINCE);
				}else{
					provinceDialog.show();	
				}
			}
			break ;
		case R.id.city_text:
			imm.hideSoftInputFromWindow(city.getWindowToken(), 0);
			if(provinceEntiy != null){
				if(cityEntiy == null || cityDialog == null){
					if(addressTask != null){
						addressTask.cancel(true);
					}
					addressTask = new AddressTask(context);
					addressTask.execute(GETCITY);
				}else{
					cityDialog.show();
				}
			}
			break ;
		default:
			break;
		}

	}

	public void dialog1(String title, String message) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("Confirm",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						int size = viewFlipper.getChildCount();
						((MyAddressLayout) viewFlipper.getChildAt(size - 2))
								.reLoad();
						viewFlipper.showPrevious();
						viewFlipper.removeView(AddressLayout.this);
						// viewFlipper.removeViewAt(size-1);

					}
				});
		builder.create().show();
	}

	public void dialog(String title, String message) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("Confirm",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();

					}
				});
		builder.create().show();
	}

	public void operate() {

		String message = null;
		if ("".equals(fullname.getText().toString())) {
			message = "fullname can not be empty!";
		}
		if ("".equals(phone.getText().toString())) {
			if (message != null) {
				message = message + " \n phone can not be empty!";
			} else {
				message = "phone can not be empty!";
			}
		}

		if ("".equals(address.getText().toString())) {
			if (message != null) {
				message = message + " \n address can not be empty!";
			} else {
				message = "address can not be empty!";
			}
		}

		if ("".equals(postalcode.getText().toString())) {
			if (message != null) {
				message = message + " \n postalcode can not be empty!";
			} else {
				message = "postalcode can not be empty!";
			}
		}

		if (message != null) {
			dialog("prompt", message);
		} else {
			new AddressTask(context).execute(actionType);
		}

	}
	class AddressTask extends AsyncTask<Integer, Integer, Object> {
		private Context context;
		ProgressDialog pdialog;
		boolean b;
		int type ;
		private RadioOnClick radioOnClick;
		public AddressTask(Context context) {
			this.context = context;
		}

		@Override
		protected void onPreExecute() {
			loadingLayout.setVisibility(View.VISIBLE);
		}
		
		@Override
		protected void onPostExecute(Object result) {
			loadingLayout.setVisibility(View.GONE);
			int size = 0;
			if(type == actionType){
				if (b) {
					dialog1("prompt", "operate success!");
				} else {
					dialog("prompt", "operate fail!");
				}
			}else if(type == GETCOUNTRY){
				radioOnClick = new RadioOnClick(0,type);
				size = countryList.size();
				String[] names = new String[countryList.size()];
				for(int i=0 ;i<size;i++){
					names[i] = countryList.get(i).getRegionName();
				}
				countryDialog = new AlertDialog.Builder(context).setTitle(
						"Country").setSingleChoiceItems(names,
						radioOnClick.getIndex(), radioOnClick).create();
				ListView radioListView = countryDialog.getListView();
				countryDialog.show();
			}else if(type == GETPROVINCE){
				radioOnClick = new RadioOnClick(0,type);
				size = provinceList.size();
				String[] names = new String[provinceList.size()];
				for(int i=0 ;i<size;i++){
					names[i] = provinceList.get(i).getRegionName();
				}
				provinceDialog = new AlertDialog.Builder(context).setTitle(
						"Province").setSingleChoiceItems(names,
						radioOnClick.getIndex(), radioOnClick).create();
				ListView radioListView = provinceDialog.getListView();
				provinceDialog.show();
			}else if(type == GETCITY){
				radioOnClick = new RadioOnClick(0,type);
				size = cityList.size();
				String[] names = new String[cityList.size()];
				for(int i=0 ;i<size;i++){
					names[i] = cityList.get(i).getRegionName();
				}
				cityDialog = new AlertDialog.Builder(context).setTitle(
						"City").setSingleChoiceItems(names,
						radioOnClick.getIndex(), radioOnClick).create();
				ListView radioListView = cityDialog.getListView();
				cityDialog.show();
			}
		}

		@Override
		protected Object doInBackground(Integer... params) {
			type = params[0];
			if(type == actionType){
				useraddress.setAddress(address.getText().toString());
				if(cityEntiy != null){
					useraddress.setCity(cityEntiy.getRegionId());
					
				}
				useraddress.setConsignee(fullname.getText().toString());
				if(countryEntiy != null){
					useraddress.setCountry(countryEntiy.getRegionId());
				}
				

				useraddress.setDistrict(0);
				useraddress.setMobile(phone.getText().toString());

				if(provinceEntiy != null){
					useraddress.setProvince(provinceEntiy.getRegionId());
				}
				useraddress.setTel(phone.getText().toString());
				useraddress.setUserId(Constants.loginResponse.getUserId());
				useraddress.setZipcode(postalcode.getText().toString());
				b = WebServiceClient.operateUserAddress(useraddress, actionType,
						com.wholesale.utils.Constants.loginResponse
								.getUserToken());
			}else if(type == GETCOUNTRY){
				countryList = WebServiceClient.getCountries();
			}else if(type == GETPROVINCE){
				provinceList = WebServiceClient.getRegionByParentParentId(countryEntiy.getRegionId(),1);
			}else if(type == GETCITY){
				cityList = WebServiceClient.getRegionByParentParentId(provinceEntiy.getRegionId(),2);
			}
			
			return null;
		}
	}
	/**
	 * 点击单选框事件
	 * 
	 */
	class RadioOnClick implements DialogInterface.OnClickListener {
		private int index;
		private int type ;
		@Override
		public void onClick(DialogInterface dialog, int which) {
//			((Button)view).setText(value);
			if(type == GETCOUNTRY){
				if(countryEntiy != null){
					if(countryEntiy.getRegionId() != countryList.get(which).getRegionId()){
						countryEntiy = countryList.get(which);
						country.setText(countryEntiy.getRegionName());
						provinceEntiy = null ;
						cityEntiy = null ;
						province.setText("");
						city.setText("");
					}
				}else{
					countryEntiy = countryList.get(which) ;
					country.setText(countryEntiy.getRegionName());
					provinceEntiy = null ;
					cityEntiy = null ;
					province.setText("");
					city.setText("");
				}
			}else if(type == GETPROVINCE){
				if(provinceEntiy != null){
					if(provinceEntiy.getRegionId() != provinceList.get(which).getRegionId()){
						provinceEntiy = provinceList.get(which);
						province.setText(provinceEntiy.getRegionName());
						cityEntiy = null ;
						city.setText("");
					}
				}else{
					provinceEntiy = provinceList.get(which);
					province.setText(provinceEntiy.getRegionName());
					cityEntiy = null ;
					city.setText("");
				}
			}else{
				cityEntiy = cityList.get(which);
				city.setText(cityEntiy.getRegionName());
			}
			setIndex(which);
			dialog.dismiss();
		}

		public RadioOnClick(int index,int type) {
			this.index = index;
			this.type = type ;
		}

		public void setIndex(int index) {
			this.index = index;
		}

		public int getIndex() {
			return index;
		}
	}
}
